﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Net;
using System.IO;
using myBoard.Framework;
using System.Diagnostics;

namespace myComics.Tools
{
    public class PageCrawler
    {
        private string _rootFolder = "http://www.gocomics.com";
        public string VirtualFolder { get; set; }
        public delegate void GoToNextStripStripAsyncCompletedHandler();
        public event GoToNextStripStripAsyncCompletedHandler GoToNextStripStripAsyncCompleted;
        public delegate void GoToPreviousStripAsyncCompletedHandler();
        public event GoToPreviousStripAsyncCompletedHandler GoToPreviousStripAsyncCompleted;
        public delegate void GetCurrentComicUrlAsyncCompletedHandler(string url);
        public event GetCurrentComicUrlAsyncCompletedHandler GetCurrentComicUrlAsyncCompleted;

        public string CurrentUrl
        {
            get
            {
                return _rootFolder + VirtualFolder;
            }
        }

        public void GetCurrentComicUrlAsync()
        {
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e)
                {
                    try
                    {
                        List<string> imgTags = GetAllImgTags();
                        foreach (string imgTag in imgTags)
                        {
                            if (imgTag.Contains(@"imgsrv.gocomics.com"))
                            {
                                e.Result = GetImgSrc(imgTag);
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionsManager.LogException("myComics", ex, false);
                        e.Result = string.Empty;
                    }
                });

            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (GetCurrentComicUrlAsyncCompleted != null)
                    GetCurrentComicUrlAsyncCompleted(e.Result as string);
            });

            bw.RunWorkerAsync();
        }


        private string GetPageSource()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_rootFolder + VirtualFolder);
            req.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            TextReader tr = new StreamReader(response.GetResponseStream());
            return tr.ReadToEnd();
        }

        private List<string> GetAllImgTags()
        {
            List<string> imgs = new List<string>();
            string source = GetPageSource();
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(@"<img\b[^>]*>(.*?)", options);

            MatchCollection matches = regex.Matches(source);
            for (int i = 0; i != matches.Count; ++i)
            {
                imgs.Add(matches[i].Value);
            }
            return imgs;
        }

        private string GetImgSrc(string imgTag)
        {
            Regex regex = new Regex(@"src='[^""\r\n]*'");

            Match match = regex.Match(imgTag);
            if (match != null)
            {
                return match.Value.Replace(@"'", string.Empty).Replace("src=", string.Empty);
            }

            return string.Empty;
        }

        public void GoToPreviousStripAsync()
        {
            GotoToPage("Previous feature");
        }

        public void GoToNextStripStripAsync()
        {
            GotoToPage("Next feature");
        }

        private void GotoToPage(string page)
        {
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e)
            {
                string source = GetPageSource();
                RegexOptions options = RegexOptions.None;
                Regex regex = new Regex(@"<a\b[^>]*>(.*?)</a>", options);

                MatchCollection matches = regex.Matches(source);
                for (int i = 0; i != matches.Count; ++i)
                {
                    if (matches[i].Value.Contains(page))
                    {
                        Regex hrefRegex = new Regex(@"href=""[^""\r\n]*""");

                        Match match = hrefRegex.Match(matches[i].Value);
                        if (match != null)
                        {
                            e.Result = match.Value.Replace(@"""", string.Empty).Replace("href=", string.Empty);
                            VirtualFolder = match.Value.Replace(@"""", string.Empty).Replace("href=", string.Empty);
                        }

                    }
                }
            });

            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (page == "Previous feature")
                {
                    if (GoToPreviousStripAsyncCompleted != null)
                        GoToPreviousStripAsyncCompleted();
                }
                if (page == "Next feature")
                {
                    if (GoToNextStripStripAsyncCompleted != null)
                        GoToNextStripStripAsyncCompleted();
                }
            });

            bw.RunWorkerAsync();
        }        
    }
}
